package resoft.jeasyform.components;

import charva.awt.Component;
import charva.awt.event.KeyAdapter;
import charva.awt.event.KeyEvent;

import java.util.List;

/**
 * <p>button for menu</p>
 * User: albert
 * Date: Sep 3, 2007
 * Time: 11:57:08 AM
 */
public class MenuItemButton extends Button {

    public Component getSwingObject() {
        Component itemButton = super.getSwingObject();
        itemButton.addKeyListener(new MenuItemKeyAdapter(getParentWindow(), this));
        return itemButton;
    }

    private class MenuItemKeyAdapter extends KeyAdapter {
        MenuItemKeyAdapter(Window parentWindow, MenuItemButton menuItem) {
            this.parentWindow = parentWindow;
            this.menuItem = menuItem;
        }

        public void keyPressed(KeyEvent keyEvent) {

        }


        public void keyTyped(KeyEvent keyEvent) {
            int keyCode = keyEvent.getKeyCode();

            if (keyCode == KeyEvent.VK_UP || keyCode == KeyEvent.VK_DOWN) {
                List components = parentWindow.listAllComponents();
                int index = components.indexOf(menuItem);
                changeNextMenuItem(index, components, keyCode);
            }
        }

        private void changeNextMenuItem(int index, List components, int keyCode) {
            if (keyCode == KeyEvent.VK_DOWN) {
                index++;
            } else {
                index--;
            }

            while (true) {
                if (keyCode == KeyEvent.VK_DOWN && index == components.size()) {
                    index = 0;
                }
                if (keyCode == KeyEvent.VK_UP && index == 0) {
                    index = components.size() - 1;
                }
                resoft.jeasyform.components.Component obj = (resoft.jeasyform.components.Component) components.get(index);
                if (obj == menuItem) {
                    break;
                }
                if (obj instanceof MenuItemButton) {
                    AcceptFocusAware control = (AcceptFocusAware) obj;
                    control.requestFocus();
                    break;
                }
                if (keyCode == KeyEvent.VK_DOWN) {
                    index++;
                } else {
                    index--;
                }
            }
        }

        private Window parentWindow;
        private MenuItemButton menuItem;
    }
}
